/*
 * TableHelper.java
 *
 * Created on Jan 17, 2012, 3:17:52 PM
 */
package util;

import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import presentation.view.MainFrame;

/**
 * Classe abstrata que serve de "molde" para todas as views listar
 * @author Owner
 */
public abstract class TableHelper extends javax.swing.JPanel {

    String[] columnNames;
    Object[][] data;
    
    public String c1 = "Alterar";;
    public String c2 = "Excluir";;
    
    private int colunaFiltro;
    private int quantidade;
    private boolean[] listaVF;
    
    private TableButton buttonExcluir;
    private TableButton buttonAlterar;
    
    private TableRowSorter<DefaultTableModel> sorter;
    
    //Funcoes a serem implementadas nas classes
    /**
     * Cria ação do botão alterar
     * @param codigo
     */
    public abstract void eventoAlterar(String codigo);
    /**
     * Cria ação do botão excluir
     * @param codigo
     */
    public abstract void eventoExcluir(String codigo);
    /**
     * Cria ação ao clicar na linha
     * @param codigo
     */
    public abstract void eventoJanelaDetalhe(String codigo);
    /**
     * Cria ação do botão adicionar
     */
    public abstract void eventoAdicionar();
    /**
     * Define nome do botão de inserção
     * @return
     */
    public abstract String getNomeButtonAdicionar();
    
    /** Creates new form TableHelper */
    public TableHelper(){
	initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jRadioButton1 = new javax.swing.JRadioButton();
        jTextField1 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setPreferredSize(new java.awt.Dimension(500, 400));

        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setText("default");
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton1ActionPerformed(evt);
            }
        });

        jTextField1.setColumns(20);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jButton2.setText("Adicionar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setText("Voltar(ESC)");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 653, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jRadioButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRadioButton1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(52, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap(54, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(50, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
	newFilter();
    }//GEN-LAST:event_jRadioButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
	eventoAdicionar();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
	MainFrame.getInstance().alterarPainel(MainFrame.getInstance().getPainelAnterior(), null);
	MainFrame.getInstance().retiraPilhaPainel();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * Função que define o nome do checkbutton utilizado para realizar a pesquisa
     * @param rb1 rabiobutton a ser apresentado
     */
    private void iniciaCheckButtons(String rb1){
	jRadioButton1.setText(rb1);
	jRadioButton1.setSelected(true);
    }
    
    /**
     * Apenas "seta" o filtro dinâmico
     */
    private void iniciaTextField(){
	jTextField1.getDocument().addDocumentListener(
	    new DocumentListener() {
		public void changedUpdate(DocumentEvent e) {
		    newFilter();
		}
		public void insertUpdate(DocumentEvent e) {
		    newFilter();
		}
		public void removeUpdate(DocumentEvent e) {
		    newFilter();
		}
	    }
	);
    }
    
    /**
     * Inicia a tabela com os dados que serão mostrados nas views listar
     * @param nomeDasColunas
     * @param data Informação a ser mostrada
     * @param nroDeLinhas
     * @param colunaFiltro coluna que servirá de filtro
     * @param radio1 nome do radiobutton do filtro
     */
    public void iniciaTabela(final String[] nomeDasColunas, Object[][] data, int nroDeLinhas, int colunaFiltro, String radio1){
	this.colunaFiltro = colunaFiltro;
	int  i= 0, j =0;
	
	//Define nome das colunas
	columnNames = new String[nomeDasColunas.length + 2];
	for( i= 0; i< nomeDasColunas.length; i ++)
	    columnNames[i] = nomeDasColunas[i];
	columnNames[i] = c1;
	columnNames[i + 1] = c2;

	//Define se eh clicavel ou nao
	listaVF = new boolean[nomeDasColunas.length + 2];
	for( i= 0; i<  nomeDasColunas.length ; i++) 
	    listaVF[i] = false;
	listaVF[i] = true;
	listaVF[i + 1] = true;

	//DEFINE A INFORMACAO DA TABELA E A QUANTIDADE DE LINHAS
	this.data = data;
	this.quantidade = nroDeLinhas;

	//DEFINE O TIPO DA TABELA
	DefaultTableModel model = new DefaultTableModel(columnNames, 0){
	    public Class getColumnClass(int columnIndex){
		return java.lang.String.class;
	    }
	    public boolean isCellEditable(int rowIndex, int columnIndex){
		return listaVF[columnIndex];
	    }
	};
	

	jTable1.setAutoCreateRowSorter(false);
	jTable1.setModel(model);
	jTable1.setSize(700, 700);

	//"POPULA" A TABELA
	Object[] objetos = new Object[columnNames.length ];
	for( i=0; i < quantidade; i++){	    
	    for ( j=0; j< columnNames.length - 2; j++ )
		objetos[j] = data[i][j];
	    objetos[j] = "";
	    objetos[j + 1]= "";
	    model.addRow(objetos);
	}
	
	
	jTable1.setAutoCreateRowSorter(true);

	//DEFINE BOTOES
	buttonAlterar = new TableButton( new TableButton.TableButtonCustomizer(){
	    public void customize(JButton button, int row, int column){
		button.setIcon(new ImageIcon(Constantes.imagePath + "edit.png") );
	    }
	});
	
	TableColumn buttonColumn = jTable1.getColumnModel().getColumn(nomeDasColunas.length);
	buttonColumn.setMaxWidth(40);
	buttonColumn.setCellRenderer(buttonAlterar);
	buttonColumn.setCellEditor(buttonAlterar);

	buttonAlterar.addHandler(new TableButton.TableButtonPressedHandler() {	
	    public void onButtonPress(int row, int column) {
		eventoAlterar(jTable1.getValueAt(row, 0).toString());
	    }
	});


	buttonExcluir = new TableButton( new TableButton.TableButtonCustomizer(){
	    public void customize(JButton button, int row, int column){
		button.setIcon(new ImageIcon(Constantes.imagePath + "remove.png") );
	    }
	});
	
	TableColumn buttonColumn2 = jTable1.getColumnModel().getColumn(nomeDasColunas.length + 1);
	buttonColumn2.setMaxWidth(40);
	buttonColumn2.setCellRenderer(buttonExcluir);
	buttonColumn2.setCellEditor(buttonExcluir);

	buttonExcluir.addHandler(new TableButton.TableButtonPressedHandler() {	
	    public void onButtonPress(int row, int column) {
		eventoExcluir(jTable1.getValueAt(row, 0).toString());
	    }
	});

	//CRIA FILTRO
	sorter = new TableRowSorter<DefaultTableModel>(model);
	jTable1.setRowSorter(this.sorter);
	jTable1.setPreferredScrollableViewportSize(new Dimension(700, 350));

	jTable1.setFillsViewportHeight(true);
	jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

	jTable1.getSelectionModel().addListSelectionListener(
	    new ListSelectionListener() {
		public void valueChanged(ListSelectionEvent event) {
		    if( jTable1.getSelectedRow() >= 0 && jTable1.getSelectedColumn() < nomeDasColunas.length) {
			eventoJanelaDetalhe( jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString());
			jTable1.clearSelection();
		    }
		}
	    });
    
	iniciaTextField();
	iniciaCheckButtons(radio1);
    }
    
    public int getAtual(String helper){
	int i, row;
	i = row = 0;
	
	while ( i < quantidade){
	    if ( data[i][0].toString().equals(helper) ){
		row = i;
		break;
	    }
	    i++;
	}
	
	return row;
    }
    
    /**
     * Define o filtro que permite a pesquisa dinâmica por nomes nas tabelas
     */
    private void newFilter() {
	RowFilter<DefaultTableModel, Object> rf = null;
	try {
	    if (jRadioButton1.isSelected()){
		rf = RowFilter.regexFilter("(?i).*"+jTextField1.getText()+".*", 1);
	    } else {
		rf = RowFilter.regexFilter("(?i).*"+jTextField1.getText()+".*", 0);
	    }
	} catch (java.util.regex.PatternSyntaxException e) {
	    return;
	}
	sorter.setRowFilter(rf);
    }
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
